<template>
  <div class="scaner" ref="scaner">
    <van-nav-bar
      title="扫一扫"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      style="background-color: #081c33;"
    />
    <div class="cover">
      <p class="line"></p>
      <span class="square top left"></span>
      <span class="square top right"></span>
      <span class="square bottom right"></span>
      <span class="square bottom left"></span>
      <p class="tips">将条形码放入框内，即可自动扫描</p>
    </div>
   <video 
      class="source"
      ref="video"
      id="video"
      :width="videoWH.width"
      :height="videoWH.height"
       autoplay
       muted
      :controls="true"
></video>
  </div>
</template>

<script>
import { userStore } from "../../stores/user.ts";
import { ElMessageBox, ElMessage } from "element-plus";
export default {
  name: 'scaner',
  props: {
    // 使用后置相机
    useBackCamera: {
      type: Boolean,
      default: true,
    },
    // 扫描识别后停止
    stopOnScaned: {
      type: Boolean,
      default: true,
    },
    drawOnfound: {
      type: Boolean,
      default: true,
    },
    // 线条颜色
    lineColor: {
      type: String,
      default: "red",
    },
    // 线条宽度
    lineWidth: {
      type: Number,
      default: 2,
    },
    // 视频宽度
    videoWidth: {
      type: Number,
      default: window.innerWidth,
    },
    // 视频高度
    videoHeight: {
      type: Number,
      default: window.innerHeight,
    },
    responsive: {
      type: Boolean,
      default: false,
    },
  },
   computed: {
    videoWH() {
      return { width: this.videoWidth, height: this.videoHeight };
    },
  },
  data() {
    return {
      decodedContent: null,
    videoStream: null,
    boundingBox: null, // 新增属性
     showPlay: false,
      showBanner: true,
      opacity: 0,
      User_Code: null,
      Interface_Code: null,
      user: null,
      t1: null,
      t2: null,
      t3: null,
      t4: null,
      ts4: null,
      sx:null,
      canvas:null
    };
  },
  created() {
    this.user = userStore();
    this.User_Code = JSON.parse(sessionStorage.getItem("UserInfo")).sUser_Code;
    this.Interface_Code = sessionStorage.getItem("item");
  },
  mounted() {
    this.startCamera()
  },
  methods: {
     startCamera() {
      try {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        // this.previousCode = null;
        // this.parity = 0;
        const facingMode = this.useBackCamera
          ? { exact: "environment" }
          : "user";
        const handleSuccess = (stream) => {
          this.$refs.video.srcObject = stream;
          const playPromise = this.$refs.video.play();
          playPromise.then(() => {
           this.initQuagga();
           this.$refs.video.focus();
          });
          this.$refs.video.focus();
        };
        navigator.mediaDevices
          .getUserMedia({
            video: {
              facingMode,
            //  width: { min: 1920},
            //   height: { min: 1480},
             width: {min: 640, ideal: 1920,max:64000},
              height: {min:480, ideal:1920,max:48000},
              frameRate: {min:30,ideal: 600, max: 600},
              focusMode: "continuous",
              focusDistance: { exact: 50 },
              
            },
          })
          .then(handleSuccess)
          .catch((error) => {
            this.$emit("error-captured", error);
          });
      }
       
      } catch (error) {
        console.error("无法访问摄像头", error);
      }
    },
    initQuagga() {
      Quagga.init(
        {
          inputStream: {
            name: "Live",
            type: "LiveStream",
            target: this.$refs.video, // 目标元素
            constraints: {
              facingMode: "environment", // 或 "user" 使用前置摄像头
            },
          },
       
          decoder: {
            readers: [
              "code_128_reader"
            ], // 支持的条码格式
          },
            locator: {
            patchSize: "medium",
            halfSample: false
          },
          numOfWorkers: 4, // Needs to be zero for accurate canvas measurement
          locate: true, // Try to locate the barcode in the image
          drawBorders: true, // Draw a border around the barcode
          drawLabels: true, // Draw a label with info about the barcode
          drawLines: true, // Draw lines between barcode elements
        
        },
        function (err) {
          if (err) {
            console.log(err);
            return;
          }
          console.log("Quagga initialization finished. Ready to start");
        Quagga.start();
        // this.$refs.video.focus();
        
        }
      );

      Quagga.onDetected(this.onQuaggaDetected);
    },
    onClickLeft() {
      this.$router.push("/souye");
    },
   
    onQuaggaDetected(result) {
      this.decodedContent = result.codeResult.code;
      console.log("一维码识别结果:", result);
      console.log("一维码识别结果:", result.codeResult.code);
      if(result.codeResult.code.length==10){
         Quagga.stop()
                axios
          .post(
            window.globalUrl.server + "Service.asmx/Get_CheckSub_Data",
            JSON.stringify({
              User_Code: this.User_Code,
              Interface_Code: this.Interface_Code,
              Check_No:result.codeResult.code,
            })
          )
          .then((res) => {
            console.log(res);
            if (res.data.RltCode == 1) {
              this.user.Get_CheckSub_Data = JSON.parse(res.data.RltData);
              sessionStorage.setItem(
                "data",
                JSON.stringify(JSON.parse(res.data.RltData))
              );
              sessionStorage.removeItem("wd");
              sessionStorage.removeItem("t1");
              sessionStorage.removeItem("t2");
              sessionStorage.removeItem("t3");
              sessionStorage.removeItem("t4");
              sessionStorage.removeItem("ts4");
              sessionStorage.removeItem("sx");
              this.user.jkwd = [];
              this.user.tableData1 = [];
              this.user.tableData2 = [];
              this.user.tableData3 = [];
              this.user.tableData4 = [];
              this.user.tableDatas4 = [];
              this.user.tableDatasx = [];
              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueInHoss",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.t1 = JSON.parse(res.data.RltData);
                    this.t1 = this.t1.map((item) => ({
                      date1: item["Hos_InDate"],
                      date2: item["Hos_OutDate"],
                      date3: item["Hos_Cause"],
                      date4: item["Hos_Group"],
                      date5: item["Hos_No"],
                    }));
                    this.user.tableData1 = this.t1;
                    sessionStorage.setItem("t1", JSON.stringify(this.t1));
                  }
                });
              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueJws_Sss",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立狗", JSON.parse(res.data.RltData));
                    this.sx = JSON.parse(res.data.RltData);
                    this.sx = this.sx.map((item) => ({
                      date1: item["Jws_qzrq"],
                      date2: item["Jws_mc"],
                    }));
                    this.user.tableDatasx = this.sx;
                    sessionStorage.setItem("sx", JSON.stringify(this.sx));
                  }
                });

              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueHomeHoss",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.t2 = JSON.parse(res.data.RltData);
                    this.t2 = this.t2.map((item) => ({
                      date1: item["Hos_InDate"],
                      date2: item["Hos_OutDate"],
                      date3: item["Hos_Cause"],
                      date4: item["Hos_Group"],
                      date5: item["Hos_No"],
                    }));
                    this.user.tableData2 = this.t2;
                    sessionStorage.setItem("t2", JSON.stringify(this.t2));
                  }
                });

              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueInoculs",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Pson_CardID: this.user.Get_CheckSub_Data.Pson_CardID,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.t3 = JSON.parse(res.data.RltData);
                    this.t3 = this.t3.map((item) => ({
                      name: item["Ino_Name"],
                      date1: item["Ino_Date"],
                      date2: item["Ino_Group"],
                    }));
                    this.user.tableData3 = this.t3;
                    sessionStorage.setItem("t3", JSON.stringify(this.t3));
                  }
                });
              axios
                .post(
                  window.globalUrl.server + "Service.asmx/GetQueUseMedis",
                  JSON.stringify({
                    User_Code: this.User_Code,
                    Interface_Code: this.Interface_Code,
                    Check_No: this.user.Get_CheckSub_Data.Check_No,
                  })
                )
                .then((res) => {
                  if (res.data.RltCode == 1) {
                    console.log("立棍", JSON.parse(res.data.RltData));
                    this.ts4 = JSON.parse(res.data.RltData);
                    this.user.tableDatas4 = this.ts4.map((item) => ({
                      name: item["Medi_Name"],
                      date1: item["Medi_UseName"],
                      date1_id: item["Medi_Use"],
                      date2: item["Medi_freqName"],
                      date2_id: item["Medi_freq"],
                      date3: item["Medi_EachDose"],
                      date4: item["Medi_EachDoseUnit"],
                      date5: item["Medi_DoseUnitName"],
                      date5_id: item["Medi_DoseUnit"],
                      date6: item["Medi_UseDate"],
                      date7: item["Medi_UseDateUnitName"],
                      date7_id: item["Medi_UseDateUnit"],
                      date8: item["Medi_MedicineYieldName"],
                      date8_id: item["Medi_MedicineYield"],
                      // date9: item["Medi_Sugg"],
                      // date9_id: item["Medi_TypeID"],
                    }));
                    sessionStorage.setItem(
                      "ts4",
                      JSON.stringify(this.user.tableDatas4)
                    );
                    this.user.tableData4 = this.user.tableDatas4.map(
                      (item) => ({
                        name: item["name"],
                        date1: item["date1"],
                        date1_id: item["date1_id"],
                        date2:
                          item["date2"] +
                          item["date3"] +
                          "次；1次" +
                          item["date4"] +
                          item["date5"],
                        date2_id: item["date2_id"],
                        date3: item["date3"],
                        date4: item["date6"] + item["date7"],
                        dates4: item["date4"],
                        date5: item["date5"],
                        date5_id: item["date5_id"],
                        date6: item["date6"],
                        date7: item["date7"],
                        date7_id: item["date7"],
                        date8: item["date8"],
                        date8_id: item["date8_id"],
                        // date9: item["date9"],
                        // date9_id: item["date9_id"],
                      })
                    );
                    sessionStorage.setItem(
                      "t4",
                      JSON.stringify(this.user.tableData4)
                    );
                  }
                });
              
              this.$router.replace("/jkwd");
              this.stopCamera();
            } else {
              if (res.data.RltCode == 0) {
                // ElMessage.error(res.data.RltMsg);
                 this.initQuagga()
              }
              sessionStorage.removeItem("t1");
              sessionStorage.removeItem("t2");
              sessionStorage.removeItem("t3");
              sessionStorage.removeItem("t4");
              sessionStorage.removeItem("ts4");
              sessionStorage.removeItem("sx")
              this.user.tableData1 = [];
              this.user.tableData2 = [];
              this.user.tableData3 = [];
              this.user.tableData4 = [];
              this.user.tableDatas4 = [];
              this.user.tableDatasx = [];
              // this.$router.replace("/jkwd");
            }
          })
          .catch((eorro) => {
            sessionStorage.removeItem("t1");
            sessionStorage.removeItem("t2");
            sessionStorage.removeItem("t3");
            sessionStorage.removeItem("t4");
            sessionStorage.removeItem("ts4");
             sessionStorage.removeItem("sx")
            this.user.tableData1 = [];
            this.user.tableData2 = [];
            this.user.tableData3 = [];
            this.user.tableData4 = [];
            this.user.tableDatas4 = [];
             this.user.tableDatasx = [];
            //  this.$router.replace("/jkwd");
          });
      }

      // 停止扫描，或者你可以根据需要继续扫描
      // this.stopCamera();
    },
    onClickLeft(){
     this.$router.replace("/jkwd");
    },
    stopCamera() {
      if (this.$refs.video && this.$refs.video.srcObject) {
        this.$refs.video.srcObject.getTracks().forEach((t) => t.stop());
         Quagga.stop()
      }
    },
  },
  beforeDestroy() {
    this.stopCamera();
  },
};
</script>
<style scoped>
.scaner {
  position: fixed;
  width: 100%;
  height: 100%;
  height: -webkit-calc(100%);
  height: -moz-calc(100%);
  height: -ms-calc(100%);
  height: -o-calc(100%);
  height: calc(100%);
}
#canvas {
    width: 100%;
  height: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  /* transform: translate(-50%,-50%); */
}
#video {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
}
.scaner .banner {
  width: 100%;
  position: absolute;
  top: 16px;
  left: 50%;
  margin-left: -170px;
  background: #fa74a2;
  border-radius: 8px;
  box-sizing: border-box;
  padding: 12px;
  opacity: 0.9;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
}
.scaner .banner .text {
  padding: 0;
  margin: 0;
  color: #ffffff;
  font-size: 12px;
  text-align: justify;
  text-align-last: left;
}
.scaner .banner .close_icon {
  display: inline-block;
  height: 24px;
  width: 24px;
  background: url("../assets/close.png") no-repeat center;
  background-size: auto 100%;
  position: absolute;
  right: 8px;
  top: 8px;
}
.scaner .cover {
  height: 110px;
  width: 220px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border: 0.5px solid #999999;
  z-index: 1111;
}
.scaner .cover .line {
  width: 200px;
  height: 1px;
  margin-left: 10px;
  background: #5f68e8;
  background: linear-gradient(
    to right,
    transparent,
    #5f68e8,
    #0165ff,
    #5f68e8,
    transparent
  );
  position: absolute;
  -webkit-animation: scan 1.75s infinite linear;
  -moz-animation: scan 1.75s infinite linear;
  -ms-animation: scan 1.75s infinite linear;
  -o-animation: scan 1.75s infinite linear;
  animation: scan 1.75s infinite linear;
  -webkit-animation-fill-mode: both;
  -moz-animation-fill-mode: both;
  -ms-animation-fill-mode: both;
  -o-animation-fill-mode: both;
  animation-fill-mode: both;
  border-radius: 1px;
}
.scaner .cover .square {
  display: inline-block;
  height: 20px;
  width: 20px;
  position: absolute;
}
.scaner .cover .square.top {
  top: 0;
  border-top: 1px solid #5f68e8;
}
.scaner .cover .square.left {
  left: 0;
  border-left: 1px solid #5f68e8;
}
.scaner .cover .square.bottom {
  bottom: 0;
  border-bottom: 1px solid #5f68e8;
}
.scaner .cover .square.right {
  right: 0;
  border-right: 1px solid #5f68e8;
}
.scaner .cover .tips {
  position: absolute;
  bottom: -48px;
  width: 100%;
  font-size: 14px;
  color: #ffffff;
  opacity: 0.8;
}
@-webkit-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-moz-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-o-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
</style>